define(function (require, exports, module) {
    var angular = require("angular");
    var common = require('./common');
    var ui = require('ui');
    var util = require('util');
    require("angular-ui");
    require("dragdrop");
    require('service/ng_service/projectService');
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/para-setting/"; //api前缀
    angular.module('ProjectReportedRules', ['ProjectService', 'ngDragDrop'])
        .service('brokerIdentities', ['$q', '$http', function ($q, $http) {
            /**
             * 所有身份数组
             */
            return function (cache) {
                if (typeof cache == 'undefined') {
                    cache = true;
                }

                var defer = $q.defer();

                $http.get(G_CONFIG.api_prefix + 'qmyx/broker/get-broker-identity-by-token', {cache: cache})
                    .success(function (res) {
                        if (res.retCode == 0) {

                            var data = res.data;
                            var item;
                            for (var i = 0; item = data[i]; i++) {
                                item.value = item.Value;
                                item.name = item.Text;
                            }

                            defer.resolve(data);
                        } else {
                            defer.reject();
                        }
                    })
                    .error(function () {
                        defer.reject();
                    });

                return defer.promise;
            };
        }])
        .controller('ReportedRulesController', ['$scope', '$http', '$q', 'brokerIdentities', function ($scope, $http, $q, brokerIdentities) {
            $scope.save = function () {
                var data = $scope.data;
                var protectionPattern = data.protectionPattern;
                var mobiles = data.customerRegRemind.Mobiles || [];
                $http.post(
                    api_prefix + "save-filing-rule-data",
                    {
                        cPatternIdentifications: getPatternIdentification,
                        proId: $scope.curProjectId,
                        sId: data.isEnableSeller.id,
                        recommendLimitId: data.recommendLimit.id,
                        recommendLimit: data.recommendLimit.value,
                        smsId: data.customerRegRemind.id,
                        eSeller: data.isEnableSeller.value,
                        smsRemind: data.customerRegRemind.IsEnable,
                        mobile: mobiles.join(';') + ";",
                        sTime: $scope.startTimeHour + ':' + $scope.startTimeMinute,
                        eTime: $scope.endTimeHour + ':' + $scope.endTimeMinute,
                        identifications: collectChangedIdentification()
                    }
                )
                    .success(function (res) {
                        ui.showSucTip();
                    })
            };

            function getPatternIdentification() {
                return JSON.stringify({
                    'suggest': _.pluck($scope.list1, 'Value'),
                    'protected': _.pluck($scope.list2, 'Value'),
                    'competition': _.pluck($scope.list3, 'Value')
                })
            }

            var cur_drag_group = 0;
            //拖动前确认动作
            $scope.beforeDrop = function (evt, ui, group) {
                var deferred = $q.defer();
                if (group != cur_drag_group) {
                    util.showDialog({
                        id: "__confirm_dialog__",
                        title: '提示',
                        fixed: true,
                        content: "<p class='beforeDropConfirm' style='margin-bottom:10px;text-indent:2em'>您正在切换客户确认模式，保存后将立即生效，此后所有新增报备将按新的模式进行处理。</p><p style='text-indent:2em'>客户确认模式切换影响面较广，请谨慎操作。</p>",
                        width: 350,
                        button: [
                            {
                                id: 'ok', value: '确定', callback: function () {
                                deferred.resolve();
                            }
                            }, {
                                id: 'cancel', value: '取消', autofocus: true, callback: function () {
                                    deferred.reject();
                                }
                            }
                        ]
                    });
                } else {
                    deferred.resolve();
                }
                return deferred.promise;
            };
            //开始拖动，目标容器显示虚线框，指示可以放置
            $scope.dragStart = function (evt, ui, item, index, group) {
                cur_drag_group = group;
                var list = $('ul.pro-mode-list'), len = list.length;
                for (var i = 0; i < len; i++) {
                    if (i != group && !$(list[i]).find('li.drag-guide').length > 0) {
                        //$(list[i]).append('<li class="cur-icon drag-guide"></li>');//用append 因为有注释节点，导致虚线框不能自动排列
                        $("li:last",$(list[i])).after('<li class="cur-icon drag-guide"></li>');
                    }
                }
            }
            //拖动元素ing  虚线框，指示可以放置
            $scope.onOver = function (evt, ui, group) {
                $($('ul.pro-mode-list')[group]).find('li.drag-guide').remove();
                var list = $('ul.pro-mode-list'), len = list.length;
                for (var i = 0; i < len; i++) {
                    if (i != group && i != cur_drag_group && !$(list[i]).find('li.drag-guide').length > 0) {
                        $("li:last",$(list[i])).after('<li class="cur-icon drag-guide"></li>');
                    }
                }
            }
            //拖动元素结束提示框消失
            $('.pro-mode-list').on("dragstop", 'li', function (event, ui) {
                $('ul.pro-mode-list').find('li.drag-guide').remove();
            });


            //添加手机号
            $scope.addTel = function () {
                common.showMobileInputDialog({
                    ok: function (mobile) {
                        var data = $scope.data;
                        $http.post(
                            api_prefix + "add-reg-remind",
                            {
                                id: data.customerRegRemind.id,
                                mobile: mobile
                            }
                        )
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.data.customerRegRemind.Mobiles = $scope.data.customerRegRemind.Mobiles ?$scope.data.customerRegRemind.Mobiles:[];
                                    $scope.data.customerRegRemind.Mobiles.push(mobile);
                                    ui.showSucTip();
                                } else {
                                    ui.showErrTip(res.errMsg);

                                }
                            });
                    }
                });
            };
            //删除短信注册提醒
            $scope.delTel = function (mobile, index) {
                util.confirm("您确定要删除吗？", {
                    ok: function () {
                        $http.post(
                            api_prefix + "del-reg-remind",
                            {
                                type: 1,
                                mobile: mobile,
                                proId: $scope.curProjectId
                            }
                        )
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    $scope.data.customerRegRemind.Mobiles = $scope.data.customerRegRemind.Mobiles ? $scope.data.customerRegRemind.Mobiles:[];
                                    $scope.data.customerRegRemind.Mobiles.splice(index, 1);
                                    ui.showSucTip();
                                } else {
                                    ui.showErrTip(res.errMsg);
                                }
                            });
                    }
                });
            };

            //指定销售员
            $scope.identifications = null;
            $scope.curIdentification = null;
            var collectChangedIdentification = function () {
                //由于存在销售员改团队问题，所以使用先删后插的方式保存
                //如果全选团队，则数据库只需要记录一笔数据，user_id等于团队id
                var changedData = {
                    'add': []
                };
                if ($scope.data.isEnableSeller.value != 1) {
                    return changedData;
                }
                $($scope.identifications).each(function (idxId, elId) {
                    $(elId.teams).each(function (idxTeam, elTeam) {
                        if (elTeam.selected) {
                            // 选择整个团队
                            changedData.add.push({
                                identification: elId.Value,
                                p_projectId: $scope.curProjectId,
                                sales_team_id: elTeam.s_sales_teamId,
                                s_userId: elTeam.s_sales_teamId
                            });
                        }
                        else {
                            $(elTeam.users).each(function (idxUser, elUser) {
                                if (elUser.selected) {
                                    // 选择用户
                                    changedData.add.push({
                                        identification: elId.Value,
                                        p_projectId: $scope.curProjectId,
                                        sales_team_id: elTeam.s_sales_teamId,
                                        s_userId: elUser.s_userId
                                    });
                                }
                            });
                        }

                    });
                });

                return changedData;
            };
            var initIdentificationInternal = function (identification, teams, id2user) {
                identification.teams = jQuery.extend(true, [], teams);

                //如果销售员直接挂在项目下，没有设置团队，则把父节点名称设置为全部
                $(identification.teams).each(function (idxTeam, elTeam) {
                    if (elTeam.s_sales_teamId == '00000000-0000-0000-0000-000000000000') {
                        elTeam.sales_team_name = '全部';
                    }
                });

                // 先取出当前身份已指定的销售员
                var selectedUsers = [];
                $(id2user).each(function (idx, el) {
                    if (el.identification.toLowerCase() == identification.Value.toLowerCase()) {
                        selectedUsers.push(el);
                    }
                });
                if (selectedUsers.length == 0) {
                    return;
                }

                // 遍历销售员，把已指定的销售员打上已选和编辑状态标识(status：1 add，2 delete 0 original)
                $(selectedUsers).each(function (idx, el) {
                    var hit = false;
                    $(identification.teams).each(function (idxTeam, elTeam) {
                        if (elTeam.s_sales_teamId.toLowerCase() == el.s_userId.toLowerCase()) {
                            // 团队全选
                            elTeam.selected = true; // 选择标识
                            $(elTeam.users).each(function (idxUser, elUser) {
                                elUser.selected = true; // 选择标识
                            });
                            hit = true;
                            return false;
                        }
                        else {
                            $(elTeam.users).each(function (idxUser, elUser) {
                                if (el.s_userId != null && el.sales_team_id != null &&
                                    el.s_userId.toLowerCase() == elUser.s_userId.toLowerCase()
                                    && el.sales_team_id.toLowerCase() == elTeam.s_sales_teamId.toLowerCase()) {
                                    elUser.selected = true; // 选择标识
                                    hit = true;
                                    return false;
                                }
                            });
                        }
                        if (hit) {
                            // 一个销售员不可能属于多个团队，所以这里可以跳出循环，优化性能
                            return false;
                        }
                    });
                });

                // 经纪人身份打上“已指定”标识
                identification.specified = getSpecified(identification.teams);
            };
            $scope.initIdentification = function (projectId) {
                $scope.loading = true;
                $http
                    .get(api_prefix + "get-identification2user", {params: {proId: projectId}})
                    .then(function (res) {
                        if (res.data.retCode == 0) {
                            $scope.identifications = res.data.data['brokeridentity'];
                            $($scope.identifications).each(function (index, element) {
                                initIdentificationInternal(element, res.data.data['teams'], res.data.data['id2user']);
                            })
                            // 默认选中第一个经纪人身份
                            if ($scope.identifications.length > 0) {
                                $scope.curIdentification = $scope.identifications[0];
                            }
                        }
                        $scope.loading = false;
                    });
            }
            $scope.selectIdentification = function (item) {
                $scope.curIdentification = item;
            };
            $scope.checkTeam = function (item) {
                $($scope.curIdentification.teams).each(function (idx, el) {
                    if (el.s_sales_teamId.toLowerCase() == item.s_sales_teamId.toLowerCase()) {
                        $(el.users).each(function (idxUser, elUser) {
                            elUser.selected = item.selected;
                        });
                    }
                });

                if (item.selected) {
                    $scope.curIdentification.specified = true;
                }
                else {
                    // 取消已指定标识
                    $scope.curIdentification.specified = getSpecified($scope.curIdentification.teams);
                }

            };

            $scope.checkUser = function (user, item) {
                if (user.selected) {
                    $scope.curIdentification.specified = true;
                }
                else {
                    item.selected = false;

                    // 取消已指定标识
                    $scope.curIdentification.specified = getSpecified($scope.curIdentification.teams);
                }

            };

            // 是否打上“已指定”标识
            var getSpecified = function (items) {
                var specified = false;
                $(items).each(function (idx, el) {
                    if (specified) {
                        return false;
                    }
                    $(el.users).each(function (idxUser, elUser) {
                        if (elUser.selected) {
                            specified = true;
                            return false;
                        }
                    });
                });
                return specified;
            };

            var update = function (projectId) {
                $http
                    .get(api_prefix + "get-filing-rule-data", {params: {proId: projectId}})
                    .then(function (res) {
                        //是否启用指定销售员
                        var data = res.data.data;
                        var enableSeller = data.isEnableSeller;
                        ui.initSwitch('#reported_autocheck', function (data) {
                            enableSeller.value = data.value;
                            if (data.value == 1) {
                                $scope.initIdentification(projectId);
                            }
                            else {
                                $scope.curIdentification = null;
                            }

                            $scope.$applyAsync();
                        });
                        if (enableSeller.value == '0') {
                            ui.offSwitch('reported_autocheck');
                        } else {
                            ui.openSwitch('reported_autocheck');
                            $scope.initIdentification(projectId);
                            $scope.$applyAsync();
                        }

                        //新客户提醒短信
                        var customerRegRemind = data.customerRegRemind;
                        ui.initSwitch('#reported_messgecheck', function (data) {
                            customerRegRemind.IsEnable = data.value;
                            $scope.$applyAsync();
                        });
                        if (customerRegRemind.IsEnable == '0') {
                            ui.offSwitch('reported_messgecheck');
                        } else {
                            ui.openSwitch('reported_messgecheck');
                        }

                        var hours = [];
                        for (var i = 0; i < 24; i++) {
                            hours.push(util.pad(i, 2));
                        }
                        $scope.hours = hours;
                        $scope.minutes = ['00', '10', '20', '30', '40', '50', '59'];
                        //发送时间段
                        var split = customerRegRemind.StartTime.split(':');
                        $scope.startTimeHour = split[0];
                        $scope.startTimeMinute = split[1];

                        split = customerRegRemind.EndTime.split(':');
                        $scope.endTimeHour = split[0];
                        $scope.endTimeMinute = split[1];

                        var mobiles = customerRegRemind.Mobiles;
                        if(typeof mobiles == 'string'){
                            mobiles = mobiles.replace(/;$/, '');
                            if (mobiles == '') {
                                customerRegRemind.Mobiles = [];
                            } else {
                                customerRegRemind.Mobiles = mobiles.split(';');
                            }
                        }

                        $scope.data = data;

                        var list1, list2, list3;

                        if ($scope.data.customerConfirmPattern && $scope.data.customerConfirmPattern.suggest) {
                            list1 = _.map($scope.data.customerConfirmPattern.suggest.Identifies, function (id) {
                                var text = $scope.data.allIdentifies[id];
                                return {'title': text, 'drag': true, 'Value': id}
                            });
                        }
                        if ($scope.data.customerConfirmPattern && $scope.data.customerConfirmPattern.protected) {
                            list2 = _.map($scope.data.customerConfirmPattern.protected.Identifies, function (id) {
                                var text = $scope.data.allIdentifies[id];
                                return {'title': text, 'drag': true, 'Value': id}
                            });
                        }
                        if ($scope.data.customerConfirmPattern && $scope.data.customerConfirmPattern.competition) {
                            list3 = _.map($scope.data.customerConfirmPattern.competition.Identifies, function (id) {
                                var text = $scope.data.allIdentifies[id];
                                return {'title': text, 'drag': true, 'Value': id}
                            });
                        }


                        $scope.list1 = list1;
                        $scope.list2 = list2;
                        $scope.list3 = list3;
                    })
            };

            $scope.$watch('curProjectId', function () {
                if ($scope.curProjectId) {
                    update($scope.curProjectId);
                }
            });
        }])
});